package com.jzo2o.customer.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 银行账户 服务实现类
 * </p>
 *
 * @author szc
 * @since 2025-09-18
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {
    /**
     * 新增或修改银行账户
     *
     * @param bankAccountUpsertReqDTO 银行账户信息
     */
    @Override
    public void upsertBankAccount(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long id = currentUser.getId();
        BankAccount bankAccount = lambdaQuery().eq(BankAccount::getId, id)
                .eq(BankAccount::getType, bankAccountUpsertReqDTO.getType()).one();
        // 判断当前用户是否存在银行账户
        if (ObjectUtils.isNull(bankAccount)){
            // 不存在则新增
            bankAccount= BeanUtil.toBean(bankAccountUpsertReqDTO, BankAccount.class);
            bankAccount.setId(id);
            save(bankAccount);
        }else {
            // 存在则修改
//            BankAccount updatedBankAccount= BeanUtil.toBean(bankAccountUpsertReqDTO, BankAccount.class);
//            updatedBankAccount.setId(id);
//            updatedBankAccount.setCreateTime(bankAccount.getCreateTime());
//            updatedBankAccount.setUpdateTime(LocalDateTime.now());
//            updateById(updatedBankAccount);
            BeanUtil.copyProperties(bankAccountUpsertReqDTO, bankAccount, CopyOptions.create().ignoreNullValue());
            bankAccount.setUpdateTime(LocalDateTime.now());
            updateById(bankAccount);
        }
    }

    /**
     * 获取当前用户银行账户信息
     *
     * @return 银行账户信息
     */
    @Override
    public BankAccountResDTO getCurrentUserBankAccount() {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long id = currentUser.getId();
        BankAccount bankAccount = getById(id);
        return BeanUtil.toBean(bankAccount,BankAccountResDTO.class);
    }
}
